﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NetOffice;
using NetOffice.ExcelApi;
using NetOffice.ExcelApi.Tools;


namespace NetOfficeDemo
{
    public partial class Form1 : Form
    {
        private List<Student> _studentLst = new List<Student>()
        {
            new Student(){Name = "张三",Age = 23,ClassName = "计算机科学与技术",Email = "zhangsan@126.com",Phone = "13800000000"},
            new Student(){Name = "李四",Age = 23,ClassName = "计算机技术",Email = "lisi@126.com",Phone = "13800000001"},
            new Student(){Name = "叶良辰",Age = 23,ClassName = "计算机应用技术",Email = "yeliangchen@126.com",Phone = "13800000002"},
            new Student(){Name = "赵日天",Age = 23,ClassName = "网络工程",Email = "zhaoritian@126.com",Phone = "13800000003"},
            new Student(){Name = "龙傲天",Age = 23,ClassName = "软件工程",Email = "longaotian@126.com",Phone = "13800000004"},
            new Student(){Name = "福尔康",Age = 23,ClassName = "大数据分析",Email = "fuerkang@126.com",Phone = "13800000000"},
        }; 
        public Form1()
        {
            InitializeComponent();
            BtnData2Excel.Click += BtnData2ExcelOnClick;
        }

        private void BtnData2ExcelOnClick(object sender, EventArgs eventArgs)
        {
            //
            NetOffice.ExcelApi.Application excelApp = new NetOffice.ExcelApi.Application();
            excelApp.DisplayAlerts = false;
            excelApp.EnableEvents = false;
            NetOffice.ExcelApi.Workbook workbook = excelApp.Workbooks.Add();
            NetOffice.ExcelApi.Worksheet worksheet = workbook.Worksheets[1] as Worksheet;
            NetOffice.ExcelApi.Tools.CommonUtils utils = new CommonUtils(excelApp);
            worksheet.Cells[1, 1].Value = "学生信息表";
            worksheet.get_Range("A1", "E1").Merge(worksheet.get_Range("A1", "E1").MergeCells);
            int rowIndex = 2;
            foreach (Student student in _studentLst)
            {
                worksheet.Cells[rowIndex, 1].Value = student.Name;
                worksheet.Cells[rowIndex, 2].Value = student.Age;
                worksheet.Cells[rowIndex, 3].Value = student.ClassName;
                worksheet.Cells[rowIndex, 4].Value = student.Email;
                worksheet.Cells[rowIndex, 5].Value = student.Phone;
                rowIndex++;
            }

            string workFile = utils.File.Combine(@"C:\", "学生信息表", NetOffice.ExcelApi.Tools.DocumentFormat.Normal);
            workbook.SaveAs(workFile);
            excelApp.Save();
            excelApp.Quit();
            excelApp.Dispose();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
